package org.jc.wx.controller;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.jc.wx.handler.WxChatMsgFactory;
import org.jc.wx.handler.WxChatMsgHandler;
import org.jc.wx.util.MessageUtil;
import org.jc.wx.util.SHA1;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;

/**
 * 功能描述
 *
 * @author wanghongqian
 * @date 2024/07/17 12:48
 */
@RestController
@Slf4j
public class CallBackController {

    private static final String token = "6l2pdfyHIeOH8CxrXbvfcf4E";

    @RequestMapping("/test")
    public String test(){
        return "test";
    }

    @Resource
    private WxChatMsgFactory wxChatMsgFactory;


    /**
     * 回调消息校验
     * @return
     */
    @GetMapping(value = "callback")
    public String callback(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr){
        log.info("验签参数，signature:{},timestamp:{},nonce:{},echostr:{}",signature,timestamp,nonce,echostr);
        String shaStr = SHA1.getSHA1(token,timestamp,nonce,"");
        if(signature.equals(shaStr)){
            return echostr;
        }
        return "unknown";
    }

    @PostMapping(value = "callback",produces = "application/xml;charset=UTF-8")
    public String callback(@RequestBody String requestBody,
                           @RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam(value = "msg_signature",required = false) String msgSignature){
        log.info("接收到微信的请求：requestBody:{}，signature:{}，timestamp:{}，nonce:{}",
                requestBody,signature,timestamp,nonce);
        Map<String,String> messageMap = MessageUtil.parseXml(requestBody);
        String msgType = messageMap.get("MsgType");
        String event = messageMap.get("Event") == null ? "" : messageMap.get("Event");
        log.info("msgType:{},event:{}", msgType, event);

        StringBuilder sb = new StringBuilder();
        sb.append(msgType);
        if (!StringUtils.isEmpty(event)) {
            sb.append(".");
            sb.append(event);
        }
        String msgTypeKey = sb.toString();
        WxChatMsgHandler wxChatMsgHandler = wxChatMsgFactory.getHandlerByMsgType(msgTypeKey);
        if (Objects.isNull(wxChatMsgHandler)) {
            return "unknown";
        }
        String replyContent = wxChatMsgHandler.dealMsg(messageMap);
        log.info("replyContent:{}", replyContent);
        return replyContent;
    }
}
